package com.example.day35.controller;

import com.example.day35.model.AjaxResult;
import com.example.day35.model.PageInfos;
import com.example.day35.model.User;
import com.example.day35.service.IUserService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping("user")
@AllArgsConstructor
public class UserController {
    private final IUserService userService;

    @RequestMapping("index")
    public String index(Model model){
        model.addAttribute("list",userService.list());
        return "user/index";
    }

    @RequestMapping("list")
    @ResponseBody
    public List<User> list(){
        return userService.list();
    }


    @RequestMapping("batchdelete")
    @ResponseBody
    public int add(String ids){
        List<Integer> idList = Arrays.asList(ids.split(",")).stream().map(item -> Integer.parseInt(item)).collect(Collectors.toList());
        return userService.batchDelete(idList);
    }


    @RequestMapping("/pageInfos")
    @ResponseBody
    public AjaxResult pageInfos(Integer pageNum,Integer pageSize){
        PageInfos<User> page = userService.findAllUsersByPage(pageNum,pageSize);
        return new AjaxResult(true,200,"成功",page);
    }

    @GetMapping("/insert")
    public String insert(){
        return "user/add";
    }

    @PostMapping("/insert")
    @ResponseBody
    public AjaxResult insert(User user){
        userService.add(user);
        return new AjaxResult(true,200,"新增成功");
    }

    @GetMapping("/update")
    public String update(Integer id,Model model){
        model.addAttribute("id",id);
        return "user/update";
    }

    @PostMapping("/update")
    @ResponseBody
    public AjaxResult update(User user){
        userService.update(user);
        return new AjaxResult(true,200,"更新成功");
    }


    @RequestMapping("/delete")
    @ResponseBody
    public AjaxResult delete(int id){
        userService.delete(id);
        AjaxResult result = new AjaxResult(true, 200, "删除成功");
        return result;
    }

}





